package leetcode;

import java.lang.reflect.Array;
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;

/**
  216. Combination Sum III

 Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

 Example 1:

 Input: k = 3, n = 7

 Output:

 [[1,2,4]]

 Example 2:

 Input: k = 3, n = 9

 Output:

 [[1,2,6], [1,3,5], [2,3,4]]
 */
public class Solution216 {
    private List<Integer> CopyList(List<Integer> from) {
        List<Integer> to = new ArrayList<Integer>();
        for (int i = 0; i < from.size(); ++i) {
            to.add(from.get(i));
        }
        return to;
    }

    private void recursiveCombineSum3(List<List<Integer>> total, List<Integer> result, int i, int k, int step, int sum, int n) {
        if (i == k - 1) {
            if (n - sum > step && n - sum < 10) {
                result.add(n - sum);
                total.add(result);
            }
        } else {
            while (sum + (step + (k - i) / 2) * (k - i) <= n) {
                step += 1;
                List<Integer> cp = CopyList(result);
                cp.add(step);
                recursiveCombineSum3(total, cp, i + 1, k, step, sum + step, n);
            }
        }
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> r = new ArrayList<List<Integer>>();
        if (k == 1) {
            r.add(new ArrayList<Integer>());
            r.get(0).add(n);
        } else {
            recursiveCombineSum3(r, new ArrayList<Integer>(), 0, k, 0, 0, n);
        }
        return r;
    }
}
